
<template>
  <div class="containers">
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-box">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="试卷名称">
          <el-input v-model="searchForm.simulationName" placeholder="输入试卷名称" clearable />
        </el-form-item>
        <el-form-item label="课程分类" prop="categoryId">
          <el-select clearable v-model="searchForm.categoryId" @change="typeHandleCourse($event)" placeholder="请选择课程分类" class="w-full">
            <el-option
              v-for="item in courseType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联课程" prop="courseId">
          <el-select clearable v-model="searchForm.courseId" placeholder="请选择关联课程" class="w-full">
            <el-option
              v-for="item in courseOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷简介">
          <el-input v-model="searchForm.synopsis" placeholder="输入简介" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="fetchData">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-btns">
      <el-button type="primary" @click="showDialog('add')">新增</el-button>
      <!-- <el-button type="success" @click="visibleHidden = true">文件导入</el-button> -->
      <!-- <el-button type="warning" @click="exportData">导出模版</el-button> -->
    </div>

    <!-- 图片卡片展示 -->
    <div class="image-card-container" v-loading="loading">
      <div v-for="item in tableData" :key="item.id" class="image-card">
        <div class="card-image">
          <img :src="item.image || defaultImage" />
          <div class="card-mask">
            <el-button type="primary" size="small" @click="showQuestionInput(item)">题目录入</el-button>
            <el-button type="primary" size="small" @click="showDialog('edit', item)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(item.id)">删除</el-button>
          </div>
        </div>
        <div class="card-content">
          <h3>{{ item.simulationName }}</h3>
          <p class="desc">{{ item.synopsis || '暂无简介' }}</p>
          <div class="card-footer">
            <span>考试: {{ item.examTime }}分钟</span>
            <span>{{ formatDate(item.createTime) }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- <TOPIC></TOPIC> -->
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :page-sizes="[12, 24, 36]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="fetchData"
      @current-change="fetchData"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="关联课程" prop="courseId">
      <el-select clearable v-model="form.courseId" placeholder="请选择关联课程" style="width: 100%;">
      <el-option
      v-for="course in coursesSelect"
      :key="course.id"
      :label="course.name"
      :value="course.id"
      />
      </el-select>
      </el-form-item>
      <el-form-item label="试卷名称" prop="simulationName">
      <el-input v-model="form.simulationName" placeholder="请输入试卷名称"/>
      </el-form-item>
      <el-form-item label="试卷简介">
      <el-input v-model="form.synopsis" type="textarea" placeholder="试卷简介" :rows="3" />
      </el-form-item>
      <el-form-item label="考试时间" prop="examTime">
      <el-input-number v-model="form.examTime" :min="1" />
      </el-form-item>
      <el-form-item label="排序">
      <el-input-number v-model="form.sort" :min="1" />
      </el-form-item>
      <el-form-item label="封面图片">
      <el-upload
            :headers="uploadHeaders"
            drag
            action="/dev-api/ossUpload/uploadImage"
            :on-progress="handleImageProgress"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-remove="handleImageRemove"
            :file-list="imageFileList"
            accept=".jpg,.png"
            list-type="picture-card"
          >
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>

            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleImageRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
      </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 题目录入 -->
    <el-dialog v-model="questionInputVisible" :title="questionInputTitle" width="98%" style="height: 98vh;">
      <TOPIC
        :simulationId="simulationId"
        :questionType="3"
        :defaultCategoryId="defualtCategoryId"
        :defaultCourseId="defualtCourse"
        v-if="questionInputVisible"
      ></TOPIC>
      </el-dialog>
      <ImportXlsxs :visible="visibleHidden" :url="url" @parentFunction="parentFunction"></ImportXlsxs>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TOPIC from '../topic/index.vue'
import { Plus } from '@element-plus/icons-vue'
import { getCourseList ,getCategoryTypeList} from '@/api/bykt/course/index';

import {listInfo,delInfo,updateInfo,addInfo,getCoursesSelect} from '@/api/bykt/info'
import {formatTimestamp} from '@/utils/date'
import { getToken } from '@/utils/auth';
import ImportXlsxs from '@/components/importXlsxs/index.vue'
const { proxy } = getCurrentInstance();

const url = ref('http://localhost/dev-api/bykt/exercise/courseExerciseImportData');
// 课程分类和课程选项
const courseType = ref([])
const courseOptions = ref([])
// 默认图片
const defaultImage = ''
const visibleHidden = ref(false)
// 数据状态
const loading = ref(false)
const tableData = ref([])
const searchForm = ref({
  simulationName: '',
  synopsis: ''
})
const pagination = ref({
  current: 1,
  size: 12,
  total: 0
})
const formRef = ref()
  // 在 script setup 中添加表单验证规则
  const rules = {
  courseId: [{ required: true, message: '请选择关联课程', trigger: 'change' }],
  simulationName: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
  examTime: [{ required: true, message: '请输入考试时间', trigger: 'blur' }]
  }

// 然后在 template 中的 el-form 上添加 :rules 属性，并给相应的表单项添加 prop
const parentFunction = (data) => {
  visibleHidden.value = false
}

const uploadHeaders = ref({
  'Authorization': `Bearer ` + getToken(), // JWT 示例
});

const dialogVisible = ref(false)
const questionInputVisible = ref(false)
const dialogTitle = ref('新增试卷')
const questionInputTitle = ref('模拟卷题目')
const coursesSelect = ref([])
const simulationId = ref(null)
const imageFileList = ref([])
const defualtCourse = ref(null)
const defualtCategoryId = ref(null)
const form = ref({
  id: null,
  simulationName: '',
  synopsis: '',
  image: '',
  examTime: 60,
  courseId:"",
  sort: undefined,
  createTime: formatTimestamp()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  const params = {
    ...searchForm.value,
    pageNum: pagination.value.current,
    pageSize: pagination.value.size
  }
  const res = await listInfo(params)
  tableData.value = res.rows
  pagination.value.total = res.total
  dialogVisible.value = false
  loading.value = false
}

// 添加接口
const addData = async (data) => {
  const res = await addInfo(data)
  if (res.code === 200) {
    ElMessage.success('新增成功')
    fetchData()
    form.value = {
      id: null,
      simulationName: '',
      synopsis: '',
      image: '',
      examTime: "",
      createTime: "",
      sort: undefined
    }
    dialogVisible.value = false
  } else {
    ElMessage.error(res.msg || '新增失败')
  }
}

// 更新接口
const updateData = async (data) => {
  const res = await updateInfo(data)
  if (res.code === 200) {
    ElMessage.success('更新成功')
    fetchData()
    form.value = {
      id: null,
      simulationName: '',
      synopsis: '',
      image: '',
      examTime: "",
      createTime: "",
      sort: undefined
    }
    dialogVisible.value = false
  } else {
    ElMessage.error(res.msg || '新增失败')
  }
}
// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    simulationName: '',
    synopsis: ''
  }
  fetchData()
  fetchCourseList()
}

const showQuestionInput = (item) => {
  console.log(item)
  simulationId.value = item.id
  questionInputVisible.value = true
  defualtCourse.value = item.courseId
  defualtCategoryId.value = item.categoryId
}

// 显示弹窗
const showDialog = (type, row) => {
  if (type === 'edit') {
    dialogTitle.value = '编辑试卷'
    form.value = { ...row }

    // 添加图片回显逻辑
    if (form.value.image) {
      imageFileList.value = [{
        name: '已上传图片',
        url: form.value.image
      }];
    } else {
      imageFileList.value = [];
    }
  } else {
    dialogTitle.value = '新增试卷'
    form.value = {
      id: null,
      simulationName: '',
      synopsis: '',
      image: '',
      examTime: "",
      sort: undefined,
      // 如果搜索条件中已选择了课程，则设置到表单中
      courseId: searchForm.value.courseId || ""
    }
    imageFileList.value = []
  }
  dialogVisible.value = true
}

const closeModal = () => {
  dialogVisible.value = false
  form.value = {
    id: null,
    simulationName: '',
    synopsis: '',
    image: '',
    examTime: "",
    sort: undefined
    // createTime: formatTimestamp()
  }
  imageFileList.value = []
}
// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // ... 原有的提交逻辑 ...
        if (form.value.id) {
          updateData(form.value)
        } else {
          addData(form.value)
        }
      } catch (error) {
        console.error('提交失败：', error)
        ElMessage.error('提交失败')
      }
    }
})
  // if (!form.value.courseId) {
  //   ElMessage.error('请选择关联课程')
  //   return
  // }

  // if (!form.value.simulationName) {
  //   ElMessage.error('请输入试卷名称')
  //   return
  // }


  // // 模拟保存
  // if (form.value.id) {
  //   updateData(form.value)
  // } else {
  //   addData(form.value)
  // }

  // dialogVisible.value = false
  // ElMessage.success('操作成功')
}



// 删除数据
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该试卷吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delInfo(id).then(res => {
      if (res.code === 200) {
        fetchData()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 获取课程列表
const requestCoursesSelect = async () => {
  // try {
    const res = await getCoursesSelect()
    if (res.code === 200) {
      // 处理课程数据
      console.log('课程列表:', res.data)
      coursesSelect.value = res.data.map(course => ({
        id: course.id,
        name: course.title
      }))
    } else {
      ElMessage.error(res.msg || '获取课程列表失败')
    }
}

const beforeImageUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
    return false;
  }
  // if (form.value.image) {
  //   // 清空现有文件列表，以便上传新文件
  //   // imageFileList.value = [];
  //   // handleImageRemove()
  // }
  return true;
}
const handleImageProgress = (event) => {
  // imageProgress.value = event.percent;
}
const handleImageSuccess = (response, file) => {
  // imageProgress.value = 0;
  // 清空现有文件列表，然后添加新上传的文件
  imageFileList.value = [];
  // 添加延迟，确保DOM更新
  setTimeout(() => {
    imageFileList.value = [{
      name: file.name,
      url: response.data
    }];
    form.value.image = response.data;
  }, 10);
}
const handleImageRemove = () => {
  // 清空图片字段
  form.value.image = "";
  imageFileList.value = [];
}

// 图片上传处理
const handleImageChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    form.value.image = e.target.result
  }
  reader.readAsDataURL(file.raw)
}



// 在 searchForm 中添加新的查询条件
searchForm.value.categoryId = ''
searchForm.value.courseId = ''

// 课程分类变化时的处理函数
const typeHandleCourse = async (categoryId) => {
  // console.log(categoryId)
  try {
    const res = await getCourseList({categoryId});
    searchForm.value.courseId = undefined;
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
}

// // 课程选择变化时的处理函数
const searchCourse = (val) => {
//   fetchData()
}

const fetchCourseList = async () => {
  try {
    const res = await getCourseList({});
    courseOptions.value = res.rows || [];
  } catch (error) {
    console.error("获取课程列表失败:", error);
  }
};
const fetchCourseTypeList = async () => {
  try {
    const res = await getCategoryTypeList({});
    courseType.value = res.rows || [];
  } catch (error) {
    console.error("获取课程分类列表失败:", error);
  }
};
// 在 onMounted 中获取课程分类数据
onMounted(async () => {
  fetchCourseTypeList()
  fetchData()
  fetchCourseList()
  requestCoursesSelect()
})
</script>

<style scoped>
/* 容器调整 */
.containers {
  width: 100%;
  min-height: 100vh;
  padding: 2vh 2vw;
  box-sizing: border-box;
}

.search-box {
  margin-bottom: 20px;
}

.action-btns {
  margin-bottom: 20px;
}

.image-card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.image-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.image-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.2);
}

.card-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.card-image:hover .card-mask {
  opacity: 1;
}

.card-content {
  padding: 15px;
}

.card-content h3 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
}

.desc {
  margin: 0 0 10px;
  font-size: 14px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.el-pagination {
  justify-content: center;
  margin-top: 20px;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 64px;
  text-align: center;
}
/* .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
} */
</style>
